Function Reference

_ArrayBinarySearch

Uses the binary search algorithm to search through a 1-dimensional array.

#include <Array.au3>
_ArrayBinarySearch ( $avArray, $iKey [, $i_Base=0] )

 

Parameters

$avArray The 1-dimensional sorted array to search on.
$iKey String or number to search for in the array.
$i_Base Optional: Start Array index for sort, normally set to 0 or 1.

 

Return Value

Success: Returns the key (index of where item is in the array).
Failure: Returns an empty string.
@Error: 0 = No error.
1 = $avArray isn't an array.
2 = $iKey is out of bounds.
3 = If the item wasn't found in the array.

 

Remarks

When doing a binary search on an array of items, the contents MUST be sorted before the search is done. Otherwise undefined results will be returned.

The array is passed to the function by reference and so doesn't use up any additional resources other than a few internal variables.

 

Related

None.

 

Example


#include <Array.au3>
Dim $avArray[10]

$avArray[0] = "JPM"
$avArray[1] = "Holger"
$avArray[2] = "Jon"
$avArray[3] = "Larry"
$avArray[4] = "Jeremy"
$avArray[5] = "Valik"
$avArray[6] = "Cyberslug"
$avArray[7] = "Nutster"
$avArray[8] = "JdeB"
$avArray[9] = "Tylo"

; sort the array to be able to do  a binary search
_ArraySort( $avArray)

; display sorted array
_ArrayDisplay( $avArray, "sorted" )

; Lookup existing entry
$iKeyIndex = _ArrayBinarySearch ( $avArray, "Jon" )
If Not @error Then
   Msgbox(0,'Entry found',' Index:' & $iKeyIndex)
Else
   Msgbox(0,'Entry Not found',' Error:' & @error)
EndIf

; Lookup None existing entry
$iKeyIndex = _ArrayBinarySearch ( $avArray, "Unknown" )
If Not @error Then
   Msgbox(0,'Entry found',' Index:' & $iKeyIndex)
Else
   Msgbox(0,'Entry Not found',' Error:' & @error)
EndIf


;
; Example 2, using an Array returned by StringSplit
;
$avArray = StringSplit("a,b,d,c,e,f,g,h,i",",")

; sort the array to be able to do  a binary search
_ArraySort( $avArray, 0, 1)

; display sorted array
_ArrayDisplay( $avArray, "sorted" )

; added 1 as second parameter to skip looking in $avArray[0]
$iKeyIndex = _ArrayBinarySearch ( $avArray, "c",1 )  
If Not @error Then
   Msgbox(0,'Entry found',' Index:' & $iKeyIndex)
Else
   Msgbox(0,'Entry Not found',' Error:' & @error)
EndIf

Exit